import { ref } from 'vue';
import type { ElegantConstRoute } from '@elegant-router/types';
import { fetchGetDynamicMenus, fetchGetRoleMenus } from '@/service/api/system-manage';
import { filterMenusByUserRoleMenus, transformBackendMenuToFrontendMenu } from '@/utils/menu';
import { useAuthStore } from '@/store/modules/auth';
import { useRouteStore } from '@/store/modules/route';

export function useDynamicMenu() {
  const menus = ref<App.Global.Menu[]>([]);
  const routes = ref<ElegantConstRoute[]>([]);
  const loading = ref(false);
  const routeStore = useRouteStore();
  const authStore = useAuthStore();

  /**
   * 将权限筛选后的菜单数组递归转换为 ElegantConstRoute[] 路由结构
   *
   * @param menuList 权限过滤后的菜单数组
   */
  function convertMenusToRoutes(menuList: any[]): ElegantConstRoute[] {
    return menuList.map((menu: any) => {
      const hasChildren = Array.isArray(menu.children) && menu.children.length > 0;
      const route: ElegantConstRoute = {
        name: menu.routeName,
        path: menu.routePath,
        component: menu.component,
        meta: {
          title: menu.menuName || menu.title || menu.label,
          icon: menu.icon,
          i18nKey: menu.i18nKey,
          keepAlive: menu.keepAlive,
          constant: menu.constant
        }
      };
      if (hasChildren) {
        route.children = convertMenusToRoutes(menu.children);
      }
      return route;
    });
  }

  /** 加载动态菜单和路由 menus.value: 经过权限过滤和格式转换后的菜单 routes.value: 经过权限过滤和格式转换后的路由 */
  async function loadMenusAndRoutes(): Promise<{ menu: App.Global.Menu[]; routes: ElegantConstRoute[] }> {
    loading.value = true;
    try {
      console.log('开始加载动态菜单...');
      const response = await fetchGetDynamicMenus();
      if (!response.data || !Array.isArray(response.data)) {
        menus.value = [];
        routes.value = [];
        console.warn('菜单数据格式错误:', response.data);
        window.$message?.error('菜单数据格式错误');
        return { menu: [], routes: [] };
      }

      // 获取用户角色菜单权限
      const userRoleMenuIds = await getUserRoleMenuIds();

      // 如果没有权限，返回空菜单
      if (!userRoleMenuIds || userRoleMenuIds.length === 0) {
        menus.value = [];
        routes.value = [];
        return { menu: [], routes: [] };
      }

      // 根据用户角色菜单权限过滤菜单
      const filteredMenus = filterMenusByUserRoleMenus(
        response.data,
        userRoleMenuIds.map(id => Number(id))
      );
      // 转换为前端菜单格式
      const transformedMenus = transformBackendMenuToFrontendMenu(filteredMenus);
      menus.value = transformedMenus;
      routeStore.setRawMenus(transformedMenus);
      // 转换为路由格式
      routes.value = convertMenusToRoutes(filteredMenus);
    } catch (error) {
      menus.value = [];
      routes.value = [];
      console.error('菜单加载异常:', error);
      window.$message?.error(`菜单加载失败: ${error instanceof Error ? error.message : '未知错误'}`);
      return { menu: [], routes: [] };
    } finally {
      loading.value = false;
    }
    return { menu: menus.value, routes: routes.value };
  }

  async function getUserRoleMenuIds(): Promise<number[] | null> {
    try {
      const userRoles = authStore.userInfo.roles;
      console.log('当前用户角色:', userRoles);

      if (!userRoles || userRoles.length === 0) {
        console.warn('用户没有角色信息，返回空菜单');
        window.$message?.warning('用户没有角色信息，无法加载菜单');
        return null;
      }

      // 使用authStore中缓存的角色信息，避免重复请求
      const allRoles = await authStore.getAllRoles();
      if (!allRoles || allRoles.length === 0) {
        console.warn('获取所有角色信息失败，返回空菜单');
        window.$message?.error('获取角色信息失败，无法加载菜单');
        return null;
      }

      const roleCodeToIdMap = new Map<string, number>();
      allRoles.forEach((role: { roleCode: string; id: number }) => {
        roleCodeToIdMap.set(role.roleCode, role.id);
      });

      const allMenuIds = new Set<number>();
      const roleMenuPromises = userRoles.map(async roleCode => {
        const roleId = roleCodeToIdMap.get(roleCode);
        if (!roleId) {
          console.warn(`未找到角色code ${roleCode} 对应的角色ID`);
          return;
        }
        const roleMenusResponse = await fetchGetRoleMenus(Number(roleId));
        if (roleMenusResponse.data && Array.isArray(roleMenusResponse.data)) {
          roleMenusResponse.data.forEach(menuId => allMenuIds.add(menuId));
        }
      });
      await Promise.all(roleMenuPromises);
      return Array.from(allMenuIds);
    } catch (error) {
      console.warn('获取用户角色菜单权限失败，返回空菜单:', error);
      window.$message?.error(`获取菜单权限失败: ${error instanceof Error ? error.message : '未知错误'}`);
      return null;
    }
  }

  return {
    loading,
    loadMenusAndRoutes
  };
}
